<?php
/**
 * 全局异常处理
 * @author SHIH
 * @date 2020/10/14 11:10
 */

namespace app\exception;

use Exception;
use app\utils\Result;
use think\exception\Handle;
use think\facade\Config;

class BusinessExceptionHandler extends Handle {

    public function render(Exception $exception) {
        if ($exception instanceof BusinessException) {
            $data = new Result($exception->getCode(), $exception->getMessage(), $exception->getErrData());
            return json($data, 200);
        } else if ($exception instanceof Exception) {
            $debugStatus = Config::get("app_debug");
            //开启debug状态，则非业务异常时会将trace信息放入data
            $errorData = $debugStatus ? $exception->getTrace() : '';
            $data = Result::fail(BusinessStatus::UNKNOW_ERROR, $errorData);
            $data->setMsg($exception->getMessage());
            return json($data, 200);
        }
        return parent::render($exception);
    }
}